#! /usr/bin/env python
#coding=utf-8


import socket
import threading
import SocketServer
import time
import pdb
import pickle
import Queue
import urllib2

lock=threading.Lock()
dllock=threading.Lock()
taskf=open('offtask.txt','a')

dbhome='/mnt/hda5/yuf/zx_suse11/ver1/offlinemgr/'
_debug_=1


q=Queue.Queue()

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        print('offmgr')
        global lock,taskf,q
        ag=1;sums=0
        #pdb.set_trace()
        data=''
        try:
            #tempdata=self.request.recv(3*1024)
            while ag:
                tempdata=self.request.recv(3*1024)
                print(tempdata)
                data=data+tempdata
                #size=len(tempdata)
###                sums=sums+size
###                print('recv sums:',sums)
                if(not tempdata ):
                    ag=0
                    break 
                time.sleep(0.02)
        except sockerror:
            pass
        #self.request.send('HTTP/1.1 200 OK\r\nDate: Wed, 14 Apr 2012 23:23:23 GMT\r\nServer: myvcff server\r\nConnection: Keep-Alive\r\nContent-Length: '+len(videodata)+'\r\nContent-Type: video/f4v\r\n\r\n')
        #self.request.send(videodata)
        #self.request.send('\r\n')
        time.sleep(0.1)
        self.request.close()

        lock.acquire()
        taskf.write(str(data)+': '+str(time.time())+ '\r\n')
        taskf.flush()#刷新输出缓存
        print(data,'\r\n')
        q.put(str(data))
        lock.release()

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass



if __name__ == "__main__":
    HOST, PORT = "localhost", 8000
    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
    ip, port = server.server_address
    server.request_queue_size=500
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.setDaemon(True)
    server_thread.start()
    time.sleep(1000)
    print("Server loop running in thread:", server_thread.name)
#    server.serve_forever()
    
